#pragma ocne

#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include "log.hpp"

class Sock
{
private:
    const static int gbacklog = 20;
public:
    Sock() {}

    static int Socket()
    {
        int listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (listensock < 0)
        {
            logMessage(FATAL, "socket error, %d: %s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "socket success!");

        int opt = 1;
        setsockopt(listensock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));

        return listensock;
    }

    static void Bind(int sock, uint16_t port, std::string ip = "0.0.0.0")
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = inet_addr(ip.c_str());

        if (bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind error, %d: %s", errno, strerror(errno));
            exit(3);
        }
        logMessage(NORMAL, "bind success!");
    }

    static void Listen(int sock)
    {
        if (listen(sock, gbacklog) < 0)
        {
            logMessage(FATAL, "listen error, %d: %s", errno, strerror(errno));
            exit(4);
        }
        logMessage(NORMAL, "listen success!");
    }

    static int Accpet(int sock, uint16_t* port, std::string* ip)  // 这里传入port和ip的地址是为了改变他们
    {
        struct sockaddr_in src;
        socklen_t len = sizeof(src);
        int serivcesock = accept(sock, (struct sockaddr*)&src, &len);
        if (serivcesock < 0)
        {
            logMessage(FATAL, "accept error, %d: %s", errno, strerror(errno));
            exit(5);
        }

        *port = ntohs(src.sin_port);
        *ip = inet_ntoa(src.sin_addr);
        return serivcesock;
    }

    static bool Connect(int sock, const uint16_t& port, const std::string& ip)
    {
        struct sockaddr_in src;
        memset(&src, 0, sizeof(src));
        src.sin_family = AF_INET;
        src.sin_port = htons(port);
        src.sin_addr.s_addr = inet_addr(ip.c_str());

        if (connect(sock, (struct sockaddr*)&src, sizeof(src)) < 0)  // 连接成功返回0
        {
            logMessage(ERROR, "connect error, %d: %s", errno, strerror(errno));
            return false;
        }
        logMessage(NORMAL, "connect success!");
        return true;
    }

    ~Sock() {}
};
